<?php

namespace app\lib\yiyan;

class yiyan
{
    private $API_KEY;
    private $SECRET_KEY;
    public function __construct()
    {

        $this->API_KEY =  'Og9xyLAiEB5F6GcMhpSfAPiT';

        $this->SECRET_KEY = 'AjU7dKAfbLm3DGKf37ImIr8c2eTP8pvM';
    }

    public function turbo($question)
    {
        $access_token = $this->getAccessToken();
        $headerss = array(
            'Content-Type: application/json'
        );
        $data = [
            "messages" => []
        ];

        $data['messages'][0] = ["role"=> "user","content" => $question];
        $data = json_encode($data);
        $response = curlPost('https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token='.$access_token,$data,$headerss);

        return $response;

    }

    private function getAccessToken(){
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => $this->API_KEY,
            'client_secret' => $this->SECRET_KEY
        );

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }
}